#include <stdlib.h>
#include <stdio.h>

#include "actions.h"

#include "actions_list.h"

sAL *AL_create_v(eAT type, va_list ap) {
    sAL *al=(sAL *)calloc(1, sizeof(sAL));
    if(!al) return NULL;

    A_init_v(&al->action, type, ap);

    return al;
}

sAL *AL_create(eAT type, ...) {
    va_list ap;
    va_start(ap, type);

    sAL *al=AL_create_v(type, ap);

    va_end(ap);

    return al;
}

sAL *AL_append_v(sAL **al, eAT type, va_list ap) {
    if(!al) return NULL;

    sAL *tmp;

    if(*al) {
        tmp=*al;
        while(tmp->next) tmp=tmp->next;
        tmp->next=AL_create_v(type, ap);
        tmp->next->prev=tmp;
        tmp=tmp->next;
    }
    else {
        tmp=*al=AL_create_v(type, ap);
    }

    return tmp;
}

sAL *AL_append(sAL **al, eAT type, ...) {
    va_list ap;
    va_start(ap, type);

    sAL *new_a=AL_append_v(al, type, ap);

    va_end(ap);

    return new_a;
}

int AL_run(sAL *al, sSynq *synq, int simu) {
    if(!al || !synq_is_usable(synq)) return 1;

    if(simu) {
        while(al) {
            if(A_run_simu(&al->action, synq)) return 1;

            al=al->next;
        }
    }
    else {
        // TODO : loop on dirs and not directly on actions => no ndirs*nactions chdir() but only ndirs
    }

    return 0;
}

void AL_remove(sAL **al, sAL *el) {
    if(!al || !*al || !el) return;

    if(el->next) el->next->prev=el->prev;

    if(el->prev) el->prev->next=el->next;
    else {
        if(*al!=el) printf("AL_remove : wtf : bad list, i correct it\n");

        *al=el->next;
     }

    A_deinit(&el->action);
    free(el);
}

void AL_free(sAL *al) {
    sAL *next;

    while(al) {
        next=al->next;

        A_deinit(&al->action);
        free(al);

        al=next;
    }
}

// ----

void AL_print(sAL *al) {
    while(al) {
        A_print(&al->action);
        printf("\n");

        al=al->next;
    }
}

void AL_print_debug(sAL *al) {
    while(al) {
        printf("[%08x:%08x,%08x]", (unsigned int)al, (unsigned int)al->prev, (unsigned int)al->next);
        A_print(&al->action);
        printf("\n");

        al=al->next;
    }
}

